<?php
/**
 * Created by PhpStorm.
 * User: zhouke
 * Date: 2018-12-19
 * Time: 10:47
 */

defined('BASEPATH') OR exit('No direct script access allowed');
header("Content-type: text/html; charset=utf-8");
class Home extends CI_Controller{
//    var $login_user;
    function __construct(){
        parent::__construct();
        $this->load->helper('cookie');
    }
    function check_login() {
        $this->login_user = bwc_user_login_get();
    }
    function display($view, $data = []) {
		$this->load->view('home/'.$view,$data);
	}
    function index($is_json = 0){
        $offset = get_parameter('offset', 0, 'get');
        $data['base_url'] = site_url('home/index/1').'?1=1';
        $list = db_get_list('article', 'xcid in(8,9,11,12) and state=1', 10, $offset, 'id desc');
        $data['list'] = $list;
        $data['xcid'] = 0;
        if ($is_json == 1) {
            if( count($list) > 0 ) {
                $this->display('article_item', $data);
            } else {
                echo 0;
            }
        } else {
            $data['rec'] = db_get_list('article', ['cid' => 1, 'is_rec' => 1, 'state' => 1], 10, '', 'id desc');
            $data['dj'] = db_get_list('article', ['cid' => 1, 'state' => 1], 10, '', 'view desc');
            $this->display('index', $data);
        }
    }
    function iirs(){
        $data = [];
        $data['title'] = '';
        $data['keywords'] = '';
        $data['description'] = '';
        $data['xcid'] = 18;
        $this->display('kj', $data);
    }
    function ci(){
        $data = [];
        $data['title'] = '';
        $data['keywords'] = '';
        $data['description'] = '';
        $data['xcid'] = 19;
        $this->display('kj', $data);
    }
    function c($xcid = 0, $is_json = 0){
        $offset = get_parameter('offset', 0, 'get');
        $data['base_url'] = site_url('home/c/'.$xcid.'/1').'?1=1';
        $where = ['cid' => 1, 'state' => 1];
        if ($xcid > 0) {
            $where['xcid'] = $xcid;
        }
        $list = db_get_list('article', $where, 10, $offset, 'id desc');
        $data['list'] = $list;
        $data['xcid'] = $xcid;
        if ($is_json == 1) {
            if( count($list) > 0 ) {
                $this->display('c_item', $data);
            } else {
                echo 0;
            }
        } else {
            $data['rec'] = db_get_list('article', ['xcid' => $xcid, 'is_rec' => 1, 'state' => 1], 10, '', 'id desc');
            $data['dj'] = db_get_list('article', ['xcid' => $xcid, 'state' => 1], 10, '', 'view desc');
            $this->display('c', $data);
        }
    }

    function v($id = 0){
        if ($id > 0) {
            $data['article'] = $article = article_get($id);
            article_view_update($id, $article['view']);
            $data['rec'] = [];
            $data['dj'] = [];
            $data['xg'] = [];
            $data['xcid'] = $article['xcid'];
            if ($article['xcid'] == 10 || $article['xcid'] == 13) {
                $data['rec'] = db_get_list('article', ['xcid' => $article['xcid'], 'is_rec' => 1, 'state' => 1], 10, '', 'id desc');
                $data['dj'] = db_get_list('article', ['xcid' => $article['xcid'], 'state' => 1], 20, '', 'view desc');
                $data['xg'] = db_get_list('article', ['xcid' => $article['xcid'], 'state' => 1], 20, '', 'id desc');
                $this->display('code_v', $data);
            } else {
                $this->display('v', $data);
                header("location:".$article['url']);
            }
        } else {
            redirect();
        }
    }

    function qr_code(){
        $data['xcid'] = 'qr_code';
        $data['rec'] = db_get_list('article', ['cid' => 1, 'is_rec' => 1, 'state' => 1], 10, '', 'id desc');
        $data['dj'] = db_get_list('article', ['cid' => 1, 'state' => 1], 10, '', 'view desc');
        $this->display('qr_code', $data);
    }
    function inter_face(){
        $data = [];
        $data['xcid'] = 'inter_face';
        $this->display('inter_face', $data);
    }
    function sq(){
        $ret = array( 'status' => false, 'info' => 'Error' );
        $this->form_validation->set_rules('name', '联系人', 'trim|required|xss_clean');
        $this->form_validation->set_rules('mobile', '电话', 'trim|required|xss_clean');
        $this->form_validation->set_rules('email', '地址', 'trim|required|xss_clean');
        $this->form_validation->set_rules('wx', '个人微信', 'trim|required|xss_clean');
        $this->form_validation->set_rules('content', '个人说明', 'trim|xss_clean');
        if ($this->form_validation->run()) {
            $mobile = get_parameter('mobile');
            $r = db_get_obj('article_user', ['mobile' => $mobile]);
            if (! $r) {
                $up_data = [
                    'name' => get_parameter('name', ''),
                    'mobile' => get_parameter('mobile', 0),
                    'content' => get_parameter('content', ''),
                    'email' => get_parameter('email', 0),
                    'wx' => get_parameter('wx', 0),
                    'ctime' => time(),
                ];
                $up_data['tk'] = base64_encode(md5($mobile.'_php'));
                $id = db_insert('article_user', $up_data);
                $ret['status'] = 1;
                $ret['info'] = '申请成功，信息审核后会将token发到你填写的邮箱里！';
            } else {
                $ret['info'] = '你输入的电话号码已经注册过，如有疑问请点本站关注频道，关注公众号给我留言说明你的情况。';
            }
        } else {
            $ret['info'] = form_error('name') . form_error('email') . form_error('content') . form_error('wx') . form_error('mobile');
            $ret['info'] = cutstr_html($ret['info']);
        }
        json_out($ret);
    }
    function ck_code(){
        $ret = array( 'status' => 0, 'info' => 'Error' );
        $psd = get_parameter('psd');
        if ($psd == 991) {
            $ret['status'] = 1;
            $ret['info'] = '查看密码正确';
            set_cookie('ck_code', 1, 31536000);
        } else {
            $ret['info'] = '查看密码错误';
        }
        json_out($ret);
    }
    function login(){
        $data['login_user'] = bwc_user_login_get();
		$this->display('login', $data);
	}
	//send mobile code
	function send_code(){
		$ret = array( 'status' => false, 'info' => 'Error' );
        $this->form_validation->set_rules ( 'mobile', '手机号码', 'trim|required|xss_clean|callback_mobile_check');
        $this->form_validation->set_rules ( 'type', '类型', 'trim|required|xss_clean');

        if ($this->form_validation->run()) {
            $mobile = get_parameter('mobile', '');
            $type = get_parameter('type', '');
            $user = bwc_user_mobile_get($mobile);
            if($user){
                echo json_encode(array('status' => 0, 'msg' => '手机号码'.$mobile.'已注册用户,请更换手机号码'));
                exit();
            }
            if( ! check_code_ip()){
                echo json_encode(array('status' => 0, 'msg' => '同一IP今日注册达到上限,请明日再来注册'));
                exit();
            }
            $ret['state'] = check_code_time($mobile, $type);
            if ($ret['state']) {
                //type 0 注册
                $data = array('mobile' => $mobile, 'code' => rand(100000, 999999), 'type' => $type, 'send_time' => time());
                $paramArr = array(
                        'method' => 'alibaba.aliqin.fc.sms.num.send',
                        'app_key' => '23300165',
                        'timestamp' => date('Y-m-d H:i:s'),
                        'format' => 'json',
                        'v' => '2.0',
                        'sign_method' => 'md5',
                        'sms_type' => 'normal',
                        'sms_free_sign_name' => '注册验证',
                        'sms_param' => '{"code":"' . $data['code'] . '","product":"霸王到"}',
                        'rec_num' => $mobile,
                        'sms_template_code' => 'SMS_4730048',
                );
                $sign = $this->createSign($paramArr);
                $strParam = $this->createStrParam($paramArr);
                $strParam .= 'sign=' . $sign;
                $url = 'http://gw.api.taobao.com/router/rest?' . $strParam;
                mobile_code($data);
                $result = file_get_contents($url);
                $ret['info'] = $result;
                $ret['status'] = 1;
                echo json_encode($ret);
            }else{
                $ret['info'] = form_error('mobile');
                json_out($ret);
            }
        }else{
            echo json_encode(array('status' => 0, 'msg' => '手机号码格式错误'));
        }
	}

	function mobile_check(){
        $mobile = get_parameter('mobile', 9);
        if ( preg_match(resource( 'mobile_match', 1 ),$mobile) ) {
            return true;
        } else{
            $this->form_validation->set_message('mobile_check', '手机号码格式错误');
            return false;
        }
    }
	function edit_psd(){
		$this->form_validation->set_rules ( 'mobile', '手机号码', 'trim|required|xss_clean');
		$this->form_validation->set_rules ( 'password', '手机号码', 'trim|required|xss_clean');
		$this->form_validation->set_rules ( 'code', '验证码', 'trim|required|xss_clean');
		if ($this->form_validation->run()){
			$mobile = getParameter('mobile', '');
			$code = getParameter('code', '');
			$password = getParameter('password', '');
			if(check_mobile_code($mobile, 'edit_psd', $code)){
				$u = get_mobile_user($mobile);
				$this->updateData('user', array('password' => md5($password), 'state' => 1), $u['id']);
				$this->_set_session($u['id'], $u);
				exit(redirect('u'));
			}else{
				myRedirect('验证码不正确','');
			}
		}
		$data['act'] = 'edit_psd';
		$data['mobile'] = '';
		$this->display('mobile_code', $data);
	}

	function createSign ($paramArr) {
		$appSecret = 'f723e2ecc63db9cfa1b4be0e49caa469';
		$sign = $appSecret;
		ksort($paramArr);
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
				$sign .= $key.$val;
			}
		}
		$sign.=$appSecret;
		$sign = strtoupper(md5($sign));
		return $sign;
	}
//组参函数
	function createStrParam ($paramArr) {
		$strParam = '';
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
				$strParam .= $key.'='.urlencode($val).'&';
			}
		}
		return $strParam;
	}

	function logout() {
		bwc_user_logout();
		redirect('home/index');
	}
	function reg() {
	    $data['login_user'] = bwc_user_login_get();
		$this->display('reg');
	}
	function email_reg() {
		$this->display('email_reg');
	}
	function inref() {
		myRedirect(
				'', site_url('index/login').'?ref='.urlencode($_SERVER['HTTP_REFERER']), FALSE
		);
	}
	function to_email_code(){
		$this->form_validation->set_rules ( 'email', '邮箱地址', 'trim|required|xss_clean');
		$this->form_validation->set_rules ( 'type', '类型', 'trim|required|xss_clean');
		$email = getParameter('email', '');
		$type = getParameter('type', '');
		$user = get_email_user($email);
		if($user){
			echo json_encode(array('status' => 0, 'msg' => '邮箱地址'.$email.'已注册用户,请更换邮箱地址'));
			exit();
		}
		$email_code = rand(100000,999999);
		$html = '<h3>玩物会员注册验证码</h3>';
		$html .= '<h1>'.$email_code.'</h1>';
		email_code(array('email' => $email, 'code' => $email_code, 'type' => $type, 'send_time' => time()));
		van5_email($email, '玩物会员注册验证码', $html);
	}
	//QQ登录
	function qqlogin(){
//		dump($this->config->item('client_id'));
//		dump($this->config->item('client_secret'));
//		exit();
		$type=isset($_REQUEST['type'])?$_REQUEST['type']:'callback';
		$_SESSION['jumpToUrl'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : base_url();
		$_SESSION['state']=	md5(uniqid(rand(), TRUE));
		$redirect_uri=str_replace('.html', '', site_url('index/qq_callback'));
		$login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&scope=get_user_info,get_info&client_id=".$this->config->item('client_id')."&redirect_uri=".urlencode($redirect_uri)
				. "&state=" . $_SESSION['state'];
		header("Location:$login_url");
	}
	function qq_callback(){
		//		header("P3P: CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
		if($_REQUEST['state'] == $_SESSION['state']){
			//拼接URL
			$redirect_uri=str_replace('.html', '', site_url('index/qq_callback'));
			$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&". "client_id=".$this->config->item('client_id')."&redirect_uri=" . urlencode($redirect_uri)
					. "&client_secret=".$this->config->item('client_secret')."&code=" . $_REQUEST["code"];
			$res = file_get_contents($token_url);
			if (strpos($res, "callback") !== false){
				$lpos = strpos($res, "(");
				$rpos = strrpos($res, ")");
				$res  = substr($res, $lpos + 1, $rpos - $lpos -1);
				$msg = json_decode($res);
				if (isset($msg->error))
				{
					echo "<h3>error:</h3>" . $msg->error;
					echo "<h3>msg  :</h3>" . $msg->error_description;
					exit;
				}
			}
			$params = array();
			parse_str($res, $params);
			$_SESSION['access_token'] = $params['access_token'];
			$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" .$params['access_token'];
			$str  = file_get_contents($graph_url);
			if (strpos($str, "callback") !== false){
				$lpos = strpos($str, "(");
				$rpos = strrpos($str, ")");
				$str  = substr($str, $lpos + 1, $rpos - $lpos -1);
			}
			$user = json_decode($str);
			if (isset($user->error)){
				echo "<h3>error:</h3>" . $user->error;
				echo "<h3>msg  :</h3>" . $user->error_description;
				exit;
			}
			//echo("Hello " . $user->openid);
			$r = $this->db->get_where('user',array('qqopenid' => $user->openid));
			//	     $ur = file_get_contents('https://graph.qq.com/user/get_user_info?access_token='.$params['access_token'].'&oauth_consumer_key=100329774&openid='.$user->openid);exit(dump($ur));
			$u = $r->row_array();//exit();
			if ($u){
				$_SESSION['qqopenid'] = $user->openid;
				$ur = file_get_contents('https://graph.qq.com/user/get_user_info?access_token='.$params['access_token'].'&oauth_consumer_key='.$this->config->item('client_id').'&openid='.$user->openid);
				$ur = json_decode($ur);
				if ($ur->nickname and $ur->gender and $ur->figureurl_2){
					$data['nickname'] = $ur->nickname;
					$data['sex'] = $ur->gender;
					$data['figureurl'] = $ur->figureurl_2;
					$this->updateData('user', $data, $u['id']);
				}
				$_SESSION['name'] = $ur->nickname;
				$_SESSION['img']=$ur->figureurl_2;
				$_SESSION['uid'] = $u['id'];
			}else {
				$_SESSION['qqopenid'] = $user->openid;
				//	    	dump($_SESSION['qqpoenid']);exit();
				//	    	exit(javascriptRedirect('',site_url('index/showreg')));
				$ur = file_get_contents('https://graph.qq.com/user/get_user_info?access_token='.$params['access_token'].'&oauth_consumer_key='.$this->config->item('client_id').'&openid='.$user->openid);
				$ur = json_decode($ur);
				$u['qqopenid'] = $user->openid;
				$u['name'] = $ur->nickname;
				$u['figureurl'] = $ur->figureurl_2;
				$u['sex'] = $ur->gender;
				$u['ctime'] = time();
				if (!$uid = $this->insertData('user', $u)){
					exit($this->config->item('emsg'));
				}
				$_SESSION['name'] = $ur->nickname;
				$_SESSION['img'] = $ur->figureurl_2;
				$_SESSION['uid'] = $uid;
			}
			redirect('u');
		}else {
			echo("The state does not match. You may be a victim of CSRF.");
		}
	}

//    function send_code() {
//        $mobile = get_parameter('mobile');
//        $type = 'reg';
//        $ret = send_mobile_code($mobile, $type);
//        json_out($ret);
//    }
}